
#include <stdio.h>
#include <dlfcn.h>
#include <string.h>
#include <stdlib.h>

static void *handle = NULL;

// typedef FILE *(FOPEN_FN)(const char *restrict pathname, const char *restrict mode);
// static FOPEN_FN *real_fopen;

#include <sys/stat.h>
#include <fcntl.h>
#include <stdarg.h>

typedef int (OPEN_FN)(const char *path, int oflag, ...);
static OPEN_FN *real_open;

// typedef int (CREAT_FN)(const char *pathname, mode_t mode);
// static CREAT_FN *real_creat = NULL;


// int creat(const char *path, mode_t mode)
// {
// 	printf("----creat file: %s\n", path);

// 	if (handle == NULL) {
// 		handle = dlopen("/lib64/libc.so.6", RTLD_LAZY);
// 	}

// 	if (handle == NULL) {
// 		printf("dlopen error libc.so\n");
// 		exit(-1);
// 	}

// 	if (real_creat == NULL) {
// 		real_creat = (CREAT_FN *)dlsym(handle, "creat");
// 		if (real_creat == NULL) {
// 			printf("dlsym error: creat\n");
// 			exit(-2);
// 		}
// 	}

// 	if (strcmp(path, "/var/tmp/locksnpslmd") == 0) {
// 		return real_creat("locksnpslmd", mode);
// 	} else {
// 		return real_creat(path, mode);
// 	}
// }

char *replace_prefix(const char *path, const char *prefix,
                     const char *new_prefix, char *new_str)
{
	char *res_str = new_str;
	while (*prefix) {
		if (*prefix != *path) {
			return NULL;
		}
		prefix++;
		path++;
	}
	while (*new_prefix) {
		*new_str = *new_prefix;
		new_prefix++;
		new_str++;
	}
	while (*path) {
		*new_str = *path;
		path++;
	}
	return res_str;
}

int open(const char *path, int oflag, ...)
{
	char buf[1024];
	printf("----open file: %s\n", path);

	if (handle == NULL) {
		handle = dlopen("/lib64/libc.so.6", RTLD_LAZY);
	}

	if (handle == NULL) {
		printf("dlopen error libc.so\n");
		exit(-1);
	}

	if (real_open == NULL) {
		real_open = (OPEN_FN *)dlsym(handle, "open");
		if (real_open == NULL) {
			printf("dlsym error: open\n");
			exit(-2);
		}
	}

	va_list args;
	va_start(args, oflag);
	mode_t mode = va_arg(args, mode_t);
	va_end(args);

	char *res;
	res = replace_prefix(path, "/var/tmp", ".", buf);
	if (res) {
		return real_open(res, oflag, mode);
	} else {
		return real_open(path, oflag, mode);
	}
}



// FILE *fopen(const char *path, const char *mode)
// {
// 	printf("----fopen file: %s\n", path);

// 	if (handle == NULL) {
// 		handle = dlopen("/lib64/libc.so.6", RTLD_LAZY);
// 	}

// 	if (handle == NULL) {
// 		printf("dlopen error libc.so\n");
// 		exit(-1);
// 	}

// 	if (real_fopen == NULL) {
// 		real_fopen = (FOPEN_FN *)dlsym(handle, "fopen");
// 		if (real_fopen == NULL) {
// 			printf("dlsym error: fopen\n");
// 			exit(-2);
// 		}
// 	}

// 	if (strcmp(path, "/var/tmp/locksnpslmd") == 0) {
// 		return real_fopen("locksnpslmd", mode);
// 	} else {
// 		return real_fopen(path, mode);
// 	}
// }